#include "login.h"
#include "ui_login.h"

Login::Login(QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::Login)
{
    ui->setupUi(this);

    connect(ui->pushButton_login, &QPushButton::clicked, this, &Login::loginUser);
    connect(ui->pushButton_register, &QPushButton::clicked, this, &Login::registerUser);
}

Login::~Login()
{
    delete ui;
}


QString Login::buildUserPasswd(const int sign)
{
    QJsonObject obj;
    obj["user"] = ui->lineEdit_user->text();
    obj["passwd"] = ui->lineEdit_passwd->text();
    obj["sign"] = sign;
    QJsonDocument doc(obj);
    return doc.toJson();
}

void Login::loginUser()
{
    QString data = buildUserPasswd(1);
    qDebug() << data;
    sock->write(data.toStdString().c_str());
}

void Login::registerUser()
{
    QString data = buildUserPasswd(2);
    sock->write(data.toStdString().c_str());
}

void Login::setSocket(QTcpSocket* _sock)
{
    sock = _sock;
}

void Login::getResult(const QJsonObject& obj)
{
    bool result = obj["result"].toBool();
    qDebug() << "result = " << result;
    if (result)
    {
        user = ui->lineEdit_user->text();
        passwd= ui->lineEdit_passwd->text();
        close();
    }
}

QString Login::getUser()
{
    return user;
}
